import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ASUS
 * Date: 2024-12-03
 * Time: 21:48
 */

public class JDBCDemo1 {
    public static void main(String[] args) throws SQLException {
        //假定数据库中有一个student 表 (id, name), 往里面插入一个数据,

        //1. 创建"数据源"
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java_1?characterEncoding=utf8&useSSL=false");
        // dataSource.setUrl();
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");


        // 2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection(); // 用java.sql; 抛异常 Alt + Enter

        // 3. 构造 SQL 语句
        String sql = "insert into student values(1, '张三')";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4. 执行 SQL 语句, 返回值就是 "这次操作影响到几行"
        int n = statement.executeUpdate();
        System.out.println("n = " + n);


        // 5. 释放必要的资源, 关闭连接.
        statement.cancel();
        connection.close();

    }
}





































